package handle

import (
	"context"
	cost "gitee.com/jinmingzhi/cdce-service/api/protos/cost/v1alpha"
	desc "gitee.com/jinmingzhi/cdce-service/api/protos/desc/v1alpha"
	exam "gitee.com/jinmingzhi/cdce-service/api/protos/exam/v1alpha"
	participate "gitee.com/jinmingzhi/cdce-service/api/protos/participate/v1alpha"
	"gitee.com/jinmingzhi/cdce-service/internal/service"
	"gitee.com/jinmingzhi/cdce-service/pkg/static"
	assetfs "github.com/elazarl/go-bindata-assetfs"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net/http"
)

var (
	costHandler        *Cost
	examHandler        *Exam
	descHandler        *Desc
	ParticipateHandler *Participate
)

func InitGlobal() {
	costHandler = NewCost(service.PaySvc)
	descHandler = NewDesc(service.UserSvc)
	examHandler = NewExam(service.SchoolReportSvc)
	ParticipateHandler = NewParticipate(service.CourseSvc, service.AreaSvc, service.SchoolReportSvc)
}

func RegisterGRPC(s *grpc.Server) {
	cost.RegisterPublicCostServer(s, costHandler)
	exam.RegisterPublicExamServer(s, examHandler)
	desc.RegisterPublicDescServer(s, descHandler)
	participate.RegisterPublicParticipateServer(s, ParticipateHandler)
}

func MustRegisterREST(mux *runtime.ServeMux, grpcListenAddress string) {
	if err := cost.RegisterPublicCostHandlerFromEndpoint(context.Background(), mux, "localhost"+grpcListenAddress, []grpc.DialOption{grpc.WithInsecure()}); err != nil {
		log.Fatal("register public payment rest error", zap.Error(err))
	}

	if err := exam.RegisterPublicExamHandlerFromEndpoint(context.Background(), mux, "localhost"+grpcListenAddress, []grpc.DialOption{grpc.WithInsecure()}); err != nil {
		log.Fatal("register public payment rest error", zap.Error(err))
	}

	if err := desc.RegisterPublicDescHandlerFromEndpoint(context.Background(), mux, "localhost"+grpcListenAddress, []grpc.DialOption{grpc.WithInsecure()}); err != nil {
		log.Fatal("register public payment rest error", zap.Error(err))
	}

	if err := participate.RegisterPublicParticipateHandlerFromEndpoint(context.Background(), mux, "localhost"+grpcListenAddress, []grpc.DialOption{grpc.WithInsecure()}); err != nil {
		log.Fatal("register public payment rest error", zap.Error(err))
	}
}

func ServeSwaggerUI(mux *http.ServeMux) {
	fileServer := http.FileServer(&assetfs.AssetFS{
		Asset:    static.Asset,
		AssetDir: static.AssetDir,
		Prefix:   "pkg/swagger",
	})
	prefix := "/ui/"
	mux.Handle(prefix, http.StripPrefix(prefix, fileServer))

}
